package com.example.test.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.test.Dao.BraendDao;
import com.example.test.Dao.GoodsDao;
import com.example.test.Dao.PicDao;
import com.example.test.Dao.TypeDao;
import com.example.test.bean.BraendType;
import com.example.test.bean.DTO.input.GoodsCreateInputDTO;
import com.example.test.bean.DTO.input.GoodsUpdateInputDTO;
import com.example.test.bean.DTO.output.GoodsListOutputDTO;
import com.example.test.bean.GoodType;
import com.example.test.bean.Goods;
import com.example.test.common.model.PageModel;
import com.example.test.common.model.R;
import com.example.test.mapper.GoodsMapper;
import com.example.test.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商品信息表 服务实现类
 * </p>
 *
 * @author dz
 * @since 2022-04-10
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private TypeDao typeDao;
    @Resource
    private BraendDao braendDao;
    @Resource
    private PicDao picDao;
    private final Logger LOGGER = LoggerFactory.getLogger(GoodsService.class);

    //根据keyword查询商品
    public R getGoodsByKeyword(String keyword, PageModel pageModel) {
        try {
            Long current = pageModel.getCurrent();
            Long size = pageModel.getSize();
            Long offset = (current - 1) * size;
            List<GoodsListOutputDTO> newList = new ArrayList<>();
            List<GoodsListOutputDTO> goodsList = goodsMapper.getByKeyword(keyword, size, offset);
            for (GoodsListOutputDTO good : goodsList) {
                good.setPicUrl(picDao.getUrlById(good.getGoodsId()));
                good.setTypeName(typeDao.getNameById(good.getGoodsType()));
                good.setBraendName(braendDao.getNameById(good.getGoodsBraend()));
                newList.add(good);
            }
            return R.success(newList);
        } catch (Exception e) {
            LOGGER.error("", e);
            return R.error("查询商品失败:" + e.getMessage());
        }


    }

    //分页查询全部商品
    public R getAllGoods(PageModel pageModel) {
        try {
            Long current = pageModel.getCurrent();
            Long size = pageModel.getSize();
            Long offset = (current - 1) * size;
            List<GoodsListOutputDTO> newList = new ArrayList<>();
            List<GoodsListOutputDTO> goodsList = goodsMapper.getAllGoods(size, offset);
            for (GoodsListOutputDTO good : goodsList) {
                good.setPicUrl(picDao.getUrlById(good.getGoodsId()));
                good.setTypeName(typeDao.getNameById(good.getGoodsType()));
                good.setBraendName(braendDao.getNameById(good.getGoodsBraend()));
                newList.add(good);
            }
            return R.success(goodsList);
        } catch (Exception e) {
            LOGGER.error("", e);
            return R.error("查询商品失败:" + e.getMessage());
        }


    }

    //根据id查询商品
    public  R getGoodsById(Long goodsId){
        try{
            Goods goods = new Goods();
            GoodsListOutputDTO goodsListOutputDTO = new GoodsListOutputDTO();
            if(goodsId != null){
                goods = goodsMapper.getById(goodsId);
                String typeName = typeDao.getNameById(goods.getGoodsType());
                String braendName = braendDao.getNameById(goods.getGoodsBraend());
                goodsListOutputDTO.setGoodsId(goodsId);
                goodsListOutputDTO.setGoodsName(goods.getGoodsName());
                goodsListOutputDTO.setTypeName(typeName);
                goodsListOutputDTO.setBraendName(braendName);
                goodsListOutputDTO.setGoodsRemain(goods.getGoodsRemain());
                goodsListOutputDTO.setSellPrice(goods.getSellPrice());
                goodsListOutputDTO.setPurchasePrice(goods.getPurchasePrice());
            }
            return R.success(goodsListOutputDTO);
        }catch(Exception e) {
            LOGGER.error("", e);
            return R.error("查询商品失败:" + e.getMessage()); }
    }

    //新增商品
    public R addGoods(GoodsCreateInputDTO goodsCreateInputDTO){
        try {
            Date time = new Date();
            Goods goods =new Goods();
            GoodType goodType = new GoodType();
            BraendType braendType = new BraendType();
            //查询是否有对应的分类，如果没有，则新增
            String newTypeName = goodsCreateInputDTO.getTypeName();
            if(newTypeName != null){
                Long typeId = typeDao.getIdByName(newTypeName);
                goods.setGoodsType(typeId);
                if(typeId == null){
                    goodType.setDeleted(false);
                    goodType.setTypeName(newTypeName);
                    int addType = typeDao.insert(goodType);
                    if(addType == 0){
                        return R.error("新建分类失败");
                    }
                    typeId = typeDao.getIdByName(newTypeName);
                    goods.setGoodsType(typeId);
                }
            }else{return R.error("typeName为空");}
            //查询是否有对应的品牌，如果没有，则新增
            String newBraendName = goodsCreateInputDTO.getBraendName();
            if(newBraendName != null){
                Long braendId = braendDao.getIdByName(newBraendName);
                goods.setGoodsBraend(braendId);
                if(braendId == null){
                    braendType.setDeleted(false);
                    braendType.setBraendName(newBraendName);
                    int addBraend = braendDao.insert(braendType);
                    if(addBraend == 0){
                        return R.error("新建品牌失败");
                    }
                    braendId = braendDao.getIdByName(newBraendName);
                    goods.setGoodsBraend(braendId);
                }
            }else{return R.error("braendName为空");}
            //设置goods
            String goodName = goodsCreateInputDTO.getGoodsName();
            goods.setDeleted(false);
            goods.setCreateTime(time);
            goods.setGoodsName(goodName);
            goods.setGoodsRemain(goodsCreateInputDTO.getGoodsRemain());
            goods.setPurchasePrice(goodsCreateInputDTO.getPurchasePrice());
            goods.setSellPrice(goodsCreateInputDTO.getSellPrice());
            int addnum = goodsMapper.insert(goods);
            if(addnum == 0){
                return R.error("新增goods失败：addnum为0");
            }
            return R.success("新增商品成功:"+ goodName);
        }catch(Exception e) {
            LOGGER.error("", e);
            return R.error("新增商品失败:" + e.getMessage());
        }
    }

    //更新商品
    public R updateGoods(GoodsUpdateInputDTO goodsUpdateInputDTO){
        try {
            Date time = new Date();
            Goods goods =new Goods();
            GoodType goodType = new GoodType();
            BraendType braendType = new BraendType();
            //查询是否有对应的分类，如果没有，则新增
            String newTypeName = goodsUpdateInputDTO.getTypeName();
            if(newTypeName != null){
                Long typeId = typeDao.getIdByName(newTypeName);
                if(typeId == null){
                    goodType.setDeleted(false);
                    goodType.setTypeName(newTypeName);
                    int addType = typeDao.insert(goodType);
                    if(addType == 0){
                        return R.error("新建分类失败");
                    }
                    typeId = typeDao.getIdByName(newTypeName);
                    goods.setGoodsType(typeId);
                }
                else {
                    goods.setGoodsType(typeId);
                }
            }else{return R.error("typeName为空");}
            //查询是否有对应的品牌，如果没有，则新增
            String newBraendName = goodsUpdateInputDTO.getBraendName();
            if(newBraendName != null){
                Long braendId = braendDao.getIdByName(newBraendName);
                goods.setGoodsBraend(braendId);
                if(braendId == null){
                    braendType.setDeleted(false);
                    braendType.setBraendName(newBraendName);
                    int addBraend = braendDao.insert(braendType);
                    if(addBraend == 0){
                        return R.error("新建品牌失败");
                    }
                    braendId = braendDao.getIdByName(newBraendName);
                    goods.setGoodsBraend(braendId);
                }
            }else{return R.error("braendName为空");}
            //设置goods
            String goodName = goodsUpdateInputDTO.getGoodsName();
            goods.setDeleted(false);
            goods.setUpdateTime(time);
            goods.setGoodsName(goodName);
            goods.setGoodsId(goodsUpdateInputDTO.getGoodsId());
            goods.setGoodsRemain(goodsUpdateInputDTO.getGoodsRemain());
            goods.setPurchasePrice(goodsUpdateInputDTO.getPurchasePrice());
            goods.setSellPrice(goodsUpdateInputDTO.getSellPrice());
            int updatenum = goodsMapper.updateById(goods);
            if(updatenum == 0){
                return R.error("更新goods失败：updatenum为0");
            }
            return R.success("更新商品成功:"+ goodName);
        }catch(Exception e) {
            LOGGER.error("", e);
            return R.error("更新商品失败:" + e.getMessage());
        }
    }

    //删除商品
    public R deleteGoods(Long goodsId){
        try {
            Date time = new Date();
            Goods goods =new Goods();
            //设置goods
            goods.setGoodsId(goodsId);

            LambdaUpdateWrapper<Goods> userQueryWrapper = Wrappers.<Goods>lambdaUpdate().eq(Goods::getGoodsId,goodsId);
            goods.setDeleted(true);
            goods.setDeletedTime(time);
//            int deletenum = goodsMapper.update(goods,userQueryWrapper);
            int deletenum = goodsMapper.logicDelete(goodsId);
            if(deletenum == 0){
                return R.error("删除goods失败：deletenum为0");
            }
            return R.success("删除商品成功:"+ goodsId);
        }catch(Exception e) {
            LOGGER.error("", e);
            return R.error("删除商品失败:" + e.getMessage());
        }
    }

//    public R PopGood(){
//        try{
//            Date time = new Date();
//            List<>
//        }catch (Exception e){
//            LOGGER.error("", e);
//            return R.error("查询失败:" + e.getMessage());
//        }
//    }
}
